from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QLabel
from v4 import STATUS


class Scheduler(object):
    def __init__(self):
        self.thread_list = []
        self.terminate = False  # 是否点击了停止

    # 1.读取表格中的每一行数据
    # 2.为每一行创建线程去执行（待执行）
    # 3.线程保存在thread_list
    def start(self, window, fn_success, fn_error, fn_stop):
        self.terminate = False
        # 1.获取表格中的每行数据 + 创建线程去执行
        for row_index in range(window.table_widget.rowCount()):

            # 状态处理，只有处于待执行状态的监控项，才执行任务
            status_text = window.table_widget.item(row_index, 4).text().strip()
            if status_text != STATUS.ready:
                continue

            sku_id = window.table_widget.item(row_index, 0).text().strip()
            price = window.table_widget.item(row_index, 3).text().strip()

            # 状态更新为监测中
            cell_status = QTableWidgetItem(STATUS.processing)
            window.table_widget.setItem(row_index, 4, cell_status)

            # 为每个任务创建线程去执行：调用jd查看详细的算法
            from utils.threads import TaskThread
            # self.thread_list.remove("线程")
            # self.destroy_thread("线程")

            # 1.拿着 sku_id 去监测
            # 2.与price做对比
            # 3.低于报警 fn_success
            t = TaskThread(sku_id, price, self, row_index, window)
            t.success_signal.connect(fn_success)
            t.error_signal.connect(fn_error)
            t.stop_signal.connect(fn_stop)
            t.start()

            # self.thread_list.append(线程)
            self.thread_list.append(t)

    def stop(self, window, fn_update_status):
        # 1.修改终止状态，每个执行中的线程都会逐步停止
        self.terminate = True

        # 2.创建监测正在运行线程个数的线程，本质上就是监测thread_list中的个数
        from utils.threads import StopThread
        t = StopThread(self, window)
        t.update_signal.connect(fn_update_status)
        t.start()

    def destroy_thread(self, thread):
        self.thread_list.remove(thread)


SCHEDULER = Scheduler()
